package com.ukefu.webim.service.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

import com.ukefu.webim.util.server.message.ChatMessage;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

public abstract interface ChatMessageRepository
        extends JpaRepository<ChatMessage, String> {
    public abstract List<ChatMessage> findByUsessionAndOrgi(String usession, String orgi);

    public abstract ChatMessage findById(String id);

    public abstract Page<ChatMessage> findByUsessionAndOrgi(String usession, String orgi, Pageable page);

    public abstract Page<ChatMessage> findByUseridAndOrgi(String userid, String orgi, Pageable page);

    public abstract List<ChatMessage> findByContextidAndOrgi(String contextid, String orgi);

    public abstract Page<ChatMessage> findByContextidAndOrgi(String contextid, String orgi, Pageable page);

    public abstract Page<ChatMessage> findByChatypeAndOrgi(String chatype, String orgi, Pageable page);

    public abstract Page<ChatMessage> findByAgentserviceidAndOrgi(String agentserviceid, String orgi, Pageable page);

    public abstract Page<ChatMessage> findByContextidAndUseridAndOrgi(String contextid, String userid, String orgi, Pageable page);

    public abstract Page<ChatMessage> findByAiidIsNotNullAndOrgi(String orgi, Pageable page);

    public abstract List<ChatMessage> findByOrgiAndAgentserviceidAndChatype(String orgi, String agentserviceid, String chatype);

    @Query(nativeQuery = true, value = "select count(*) from uk_chat_message WHERE touser = ?1 and readstatus = ?2 and orgi = ?3")
    public abstract int countNotReadMessagesByUserId(String userId, Integer readStatus, String orgi);

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Query(nativeQuery = true, value = "update uk_chat_message set readstatus = 1 where touser = ?1 and orgi = ?2")
    public abstract void updateMessageReadStatus(String touser, String orgi);
}
